layui.define(['jquery','dialog','upload','layer','layedit'],function(exports){
    var $ = layui.jquery;
    var dialog = layui.dialog;
    var upload = layui.upload,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        layedit = layui.layedit;
    var baseutil = {
        /**
         * Post请求
         * @param url 请求连接
         * @param params 参数
         * @param successFn 成功方法
         */
        post:function(url,params,successFn){
            $.post(url,params,function(result){
                successFn(result);
            },"json");
        },
        /**
         * Get请求
         * @param url 请求连接
         * @param params 参数
         * @param successFn 成功方法
         */
        get:function(url,params,successFn){
            $.get(url,params,function (result) {
                successFn(result);
            });
        },
        acceptFile:function(objectId,successFn){
            this.post("/sysFile/list",{objectId:objectId},successFn);
        },
        /**
         * 加载已存在图片
         * @param url 请求连接
         * @param params 参数
         * @param successFn 成功方法
         */
        showImageList:function () {

        },
        uploadImage:function(elem,params,resultId){

            upload.render({
                elem: elem //绑定元素
                ,url: '/file/picture' //上传接口
                ,data:params //可选项。额外的参数，如：{id: 123, abc: 'xxx'}
                ,done: function(result){
                    debugger
                    if("success"==result.code){
                        var imgObj=$(elem).find("img");
                        imgObj.attr("src",result.result);
                        $("#resultId").attr("src",result.result);
                        imgObj.show();
                        $(elem).find(".btnctn").hide();
                    }else{
                        dialog.msg(result.msg);
                    }
                }
                ,error: function(){
                    //请求异常回调
                    dialog.msg("请求异常");
                }
            });
        },
        importExecl:function(elem,url,successFn){
            //导入execl
            var uploadListIns = upload.render({
                elem: elem
                ,url:url
                ,accept: 'file'
                ,before: function(obj){
                    layer.load(); //上传loading
                }
                ,done: function(result){
                    layer.closeAll('loading');
                    dialog.msg(result.msg);
                }
                ,error: function(){
                    layer.closeAll('loading');
                    //请求异常回调
                    dialog.msg("请求异常");
                }
            });
        },
        uploadSingleFile:function(elem,params,successFn){
            //展示列表位置
            var uploadListIns = upload.render({
                elem: elem
                ,url:'/file/fileUpload'
                ,accept: 'file'
                ,multiple: true
                ,data:params //可选项。额外的参数，如：{id: 123, abc: 'xxx'}
                ,auto: true
                ,allDone: function(obj){ //当文件全部被提交后，才触发
                    successFn(objectId);
                }
                ,done: function(res, index, upload){ //每个文件提交一次触发一次。详见“请求成功的回调”
                    debugger
                    if(res.code == 0){ //上传成功

                    }else{
                        dialog.msg(res.msg);
                    }
                }
            });
        },
        uploadMultiFile:function(showElem,elem,catalog,objectId,successFn){
            if(objectId==null||objectId==""){
                objectId=new Date().getTime()+this.acceptRandom(8);
            }
            //展示列表位置
            var demoListView = showElem;
            var uploadListIns = upload.render({
                elem: elem
                ,url:'/file/fileUpload'
                ,accept: 'file'
                ,multiple: true
                ,data:{catalog: catalog,objectId:objectId} //可选项。额外的参数，如：{id: 123, abc: 'xxx'}
                ,auto: true
                ,allDone: function(obj){ //当文件全部被提交后，才触发
                    successFn(objectId);
                }
                ,done: function(res, index, upload){ //每个文件提交一次触发一次。详见“请求成功的回调”
                    if(res.code == 0){ //上传成功
                        var tr = $(['<tr id="upload-'+ res.data.id +'">'
                            ,'<td>'+ res.data.fileName +'</td>'
                            ,'<td>'+ (res.data.fileSize/1014).toFixed(1) +'kb</td>'
                            ,'<td>上传成功</td>'
                            ,'<td class="center">'
                            ,'<button data-id="'+ res.data.id +'" class="layui-btn layui-btn-danger layui-btn-sm demo-delete">删除</button>'
                            ,'</td>'
                            ,'</tr>'].join(''));
                        //删除
                        tr.find('.demo-delete').on('click', function(){
                            var id=$(this).attr("data-id");
                            dialog.confirm({
                                message:'您确定要删除该附件吗',
                                success:function(){
                                    baseutil.post("/sysFile/deleteById",{id:id},function (result) {
                                        if(0==result.code){
                                            tr.remove();
                                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                                        }else{
                                            top.layer.msg(result.msg);
                                        }
                                    });
                                },
                                cancel:function(){
                                }
                            })
                         });
                        demoListView.append(tr);
                    }else{
                        dialog.msg(res.msg);
                    }
                }
            });
        },
        uploadMultImage:function(showElem,elem,catalog,objectId,successFn){
            if(objectId==null||objectId==""){
                objectId=new Date().getTime()+this.acceptRandom(8);
            }
            //展示列表位置
            var demoListView = showElem;
            var uploadListIns = upload.render({
                elem: elem //'#test2'
                ,url:'/sysFile/singleImage'
                ,accept: 'file'
                ,multiple: true
                ,data:{catalog: catalog,objectId:objectId} //可选项。额外的参数，如：{id: 123, abc: 'xxx'}
                ,auto: true
                ,allDone: function(obj){ //当文件全部被提交后，才触发
                    successFn(objectId);
                }
                ,done: function(res, index, upload){ //每个文件提交一次触发一次。详见“请求成功的回调”
                    if(res.code == 0){ //上传成功
                        var tr = $(['' +
                        '<li><div class="delepictbn" style="z-index:2" ><span class="iconfont delebtn" onclick="delImg('+"'"+ res.data.id+"'"+')">&#xe637;</span><span class="iconfont" onclick="viewShow('+"'"+ res.data.path+"'"+')">&#xe66e;</span></div><img src="'+ res.data.path +'"alt="'+ res.data.fileName +'" style="width: 80px;height: 80px;margin: 5px;z-index:1" class="layui-upload-img" ></li>'+
                       // '<img src="'+ res.data.path +'" alt="'+ res.data.fileName +'" style="width: 80px;height: 80px;margin: 5px;" class="layui-upload-img">'+
                            '<input style="display: none" value="'+res.data.id +'">'

                        ].join(''));
                        //删除
                        demoListView.append(tr);
                        show();
                    }else{
                        dialog.msg(res.msg);
                    }
                }
            });
        }
        /**
         * 获取随机数
         * @param num 随机个数
         * @returns {string}
         */
        ,acceptRandom:function(num){
            var rnd="";
            for(var i=0;i<num;i++)
                rnd+=Math.floor(Math.random()*10);
            return rnd;
        }
        ,layeditBuild:function(objId,height){
            if(height==null||height==""){
                height=400;
            }
            layedit.set({
                uploadImage: {
                    url: '/sysFile/layEditUpload' //接口url
                    ,data:{catalog:"/sys/layedit"} //可选项。额外的参数，如：{id: 123, abc: 'xxx'}
                    ,type: 'post' //默认post
                }
            });
            var index=layedit.build(objId, {
                tool: ['strong' //加粗
                    , 'italic' //斜体
                    , 'underline' //下划线
                    , 'del' //删除线
                    , '|' //分割线
                    , 'left' //左对齐
                    , 'center' //居中对齐
                    , 'right' //右对齐
                    , 'link' //超链接
                    , 'unlink' //清除链接
                    , 'image' //插入图片
                ],
                height: height
            });
            return index;
        },layeditBuildContent:function(index){
            return layedit.getContent(index);
        },acceptCheckBoxIds:function (name) {
            var ids =[];//接收对象
            var r = document.getElementsByName(name);
            for (var i = 0; i < r.length; i++) {
                if (r[i].checked) {
                    ids.push(r[i].value);
                }
            }
            if(ids==null||ids.length<=0){
                return "";
            }
            return ids.join(",");
        }
    };
    //输出baseutil接口
    exports('baseutil', baseutil);


});


function show() {
    $(".layui-upload-list ul li").mouseover(function () {
        $(this).children('.delepictbn').show();
    });
    $(".layui-upload-list ul li").mouseout(function () {
        $(this).children('.delepictbn').hide();
    });
}

function  viewShow(param) {
    layer.open({
        type:1
        ,title:false
        ,closeBtn:0
        ,skin:'layui-layer-nobg'
        ,shadeClose:true
        ,content:'<img src="'+param +'" style="max-height:600px;max-width:100%;">'
        ,scrollbar:false
    })
}

function  delImg(param) {
    var id=param;
    $.post(
        $.ajax({
            type:"post",
            data:{id:id},
            url:"/sysFile/deleteById",
            success:function (data) {
                if(data.code=="0"){
                    layer.msg('删除图片成功');
                }else{
                    layer.msg('删除图片失败，请联系管理员');
                }
            }
        })
    );
    $("#manypic").on("click",".delebtn",function(){
        $(this).parent().parent('li').remove();
    });
}